var gitClone = require('download-git-repo')
var path = require('path')
var exists = require('fs').existsSync
var rm = require('rimraf').sync
var ora = require('ora')

var gitDictionary = require('./git-dict.json')
var downloadPath = require('./config.js').downloadPath
if (exists(downloadPath)) {
  rm(downloadPath)
}

function getGitRepo (key) {
  var match = key.split('#')
  if (match.length === 2) {
    return gitDictionary[match[0]] + '#' + match[1]
  } else {
    return gitDictionary[key]
  }
}

module.exports = {
  download: function (repoKey, src) {
    var spinner = ora('downloading template')
    spinner.start()
    return new Promise(function (resolve, reject) {
      gitClone(getGitRepo(repoKey), src, { clone: true}, function (err) {
        spinner.stop()
        if (err) {
          return reject(err)
        }
        resolve()
      })
    })
  }
}
